var BASE_URL = getApp().globalData.BASE_URL

Page({
  data: {
    canvas: null,
    context: null,

    // 前一点
    preX: 0,
    preY: 0,
    id:''
  },

  onShow: function () {
    const that = this;

    // 获取画布
    const query = wx.createSelectorQuery()
    query.select('#myCanvas')
      .fields({
        node: true,
        size: true
      })
      .exec((res) => {
        const canvas = res[0].node
        const ctx = canvas.getContext('2d')

        const dpr = wx.getSystemInfoSync().pixelRatio
        canvas.width = res[0].width * dpr
        canvas.height = res[0].height * dpr
        ctx.scale(dpr, dpr)

        // 设置笔触信息
        ctx.strokeStyle = '#213123'
        ctx.lineWidth = 2
        ctx.font = "20px Arial"

        that.setData({
          canvas: canvas,
          context: ctx
        })
      })
  },

  /**记录开始点 */
  bindtouchstart: function (e) {
    console.log(e)
    let context = this.data.context
    let curX = e.changedTouches[0].x
    let curY = e.changedTouches[0].y

    context.beginPath()
    context.moveTo(curX, curY)

    this.data.preX = curX
    this.data.preY = curY
  },

  /**记录移动点，刷新绘制 */
  bindtouchmove: function (e) {
    let context = this.data.context
    let preX = this.data.preX
    let preY = this.data.preY
    let curX = e.changedTouches[0].x
    let curY = e.changedTouches[0].y

    let deltaX = Math.abs(preX - curX)
    let deltaY = Math.abs(preY - curY)

    // 相差大于3像素的时候作二阶贝塞尔曲线
    if (deltaX >= 3 || deltaY >= 3) {
      // 前后两点中心点
      let centerX = (preX + curX) / 2
      let centerY = (preY + curY) / 2

      //这里以前一点作为控制点，中心点作为终点，起始点为上一次的中点，很流畅啊！
      context.quadraticCurveTo(preX, preY, centerX, centerY);
      context.stroke();

      this.data.preX = curX
      this.data.preY = curY
    }
  },

  /**清空画布 */
  clear: function () {
    let context = this.data.context
    let canvas = this.data.canvas

    context.clearRect(0, 0, canvas.width, canvas.height);

    context.strokeStyle = '#000000'
    context.lineWidth = 2
    context.font = "20px Arial"
  },

  /**导出图片 */
  export: function () {
    const that = this;
    wx.showLoading({
      title: '正在生成签名...',
    })
    wx.canvasToTempFilePath({
      canvas: that.data.canvas,
      success(res) {
        wx.hideLoading()
        let base64_img = wx.getFileSystemManager().readFileSync(res.tempFilePath, 'base64')
          base64_img = 'data:image/png;base64,' + base64_img
          //打印出base64字符串，可复制到网页校验一下是否是你选择的原图片呢
          that.setData({
            //这里是为了预览功能做准备
            Imgurl: res.tempFilePath
          });
          console.log('签好了','res.tempFilePath')

          // 将图片保存到服务器
          var userinfo = wx.getStorageSync("USER")
          wx.request({
            url: `${BASE_URL}/baoxian/qianmingimagenew`, //仅为示例，并非真实的接口地址
            data: {
              iiiid: that.data.id,
              imgmm: base64_img,
            },
            header: {
              'content-type': 'application/x-www-form-urlencoded' // 默认值
            },
            method: "post",
            success(res) {
              console.log(res)
              wx.redirectTo({
                url: `../sureorder/index?id=${that.data.id}`
              })
            },
            fail: function (res) {
              wx.showModal({
                title: '错误提示',
                content: '保存失败请重新签名',
                showCancel: false,
              })
            }
          })
      },
      fail() {
        wx.hideLoading()
        wx.showToast({
          title: '生成图片失败',
          icon: 'none',
          duration: 1000
        })
      }
    })
  },
  onLoad: function (options) {
    this.setData({
      id:options.id
    })
  },
})